import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import DatePicker from 'react-datepicker';
import { format, addDays, isToday } from 'date-fns';
import { AppointmentSchema } from '../lib/schema';
import { getAvailableTimeSlots, createAppointment } from '../lib/db';
import 'react-datepicker/dist/react-datepicker.css';

export default function Home() {
  const [selectedDate, setSelectedDate] = useState(null);
  const [availableSlots, setAvailableSlots] = useState([]);
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  
  const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: zodResolver(AppointmentSchema),
  });

  const timeSlots = [
    '09:00-09:30', '09:30-10:00', '10:00-10:30', '10:30-11:00',
    '11:00-11:30', '11:30-12:00', '13:00-13:30', '13:30-14:00',
    '14:00-14:30', '14:30-15:00', '15:00-15:30', '15:30-16:00',
    '16:00-16:30', '16:30-17:00'
  ];

  const handleDateChange = async (date) => {
    setSelectedDate(date);
    setSelectedSlot(null);
    
    const formattedDate = format(date, 'yyyy-MM-dd');
    const bookedSlots = await getAvailableTimeSlots(formattedDate);
    
    setAvailableSlots(bookedSlots);
  };

  const onSubmit = async (data) => {
    if (!selectedSlot) return;
    
    setIsSubmitting(true);
    
    try {
      await createAppointment({
        ...data,
        appointment_date: format(selectedDate, 'yyyy-MM-dd'),
        time_slot: selectedSlot,
      });
      
      setIsSuccess(true);
    } catch (error) {
      console.error('Error creating appointment:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isSuccess) {
    return (
      <div className="container">
        <div className="bg-teal-100 border border-teal-500 text-teal-700 px-4 py-3 rounded mb-4">
          <h2 className="font-bold text-xl mb-2">预约成功!</h2>
          <p>感谢您的预约，我们会在预约时间前与您确认。</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container">
      <h1 className="text-2xl font-bold mb-6">咨询预约系统</h1>
      
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-6">
          <label className="block text-gray-700 mb-2">选择日期</label>
          <DatePicker
            selected={selectedDate}
            onChange={handleDateChange}
            minDate={new Date()}
            maxDate={addDays(new Date(), 30)}
            placeholderText="点击选择日期"
            className="border rounded px-3 py-2 w-full"
            filterDate={(date) => {
              // 只允许工作日预约
              return date.getDay() !== 0 && date.getDay() !== 6;
            }}
          />
        </div>

        {selectedDate && (
          <div className="mb-6">
            <label className="block text-gray-700 mb-2">
              选择时间段 ({format(selectedDate, 'yyyy年MM月dd日')})
            </label>
            <div className="grid grid-cols-2 gap-2">
              {timeSlots.map((slot) => {
                const isBooked = availableSlots.includes(slot);
                const isSelected = selectedSlot === slot;
                
                return (
                  <button
                    key={slot}
                    type="button"
                    onClick={() => !isBooked && setSelectedSlot(slot)}
                    className={`time-slot ${isBooked 
                      ? 'time-slot-booked' 
                      : isSelected 
                        ? 'time-slot-selected' 
                        : 'time-slot-available'}`}
                    disabled={isBooked}
                  >
                    {slot}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <div className="mb-4">
          <label className="block text-gray-700 mb-2">姓名</label>
          <input
            type="text"
            {...register('name')}
            className="border rounded px-3 py-2 w-full"
          />
          {errors.name && <p className="text-red-500 text-sm mt-1">{errors.name.message}</p>}
        </div>

        <div className="mb-4">
          <label className="block text-gray-700 mb-2">手机号码</label>
          <input
            type="tel"
            {...register('phone')}
            className="border rounded px-3 py-2 w-full"
          />
          {errors.phone && <p className="text-red-500 text-sm mt-1">{errors.phone.message}</p>}
        </div>

        <div className="mb-4">
          <label className="block text-gray-700 mb-2">微信(选填)</label>
          <input
            type="text"
            {...register('wechat')}
            className="border rounded px-3 py-2 w-full"
          />
        </div>

        <div className="mb-4">
          <label className="block text-gray-700 mb-2">邮箱(选填)</label>
          <input
            type="email"
            {...register('email')}
            className="border rounded px-3 py-2 w-full"
          />
          {errors.email && <p className="text-red-500 text-sm mt-1">{errors.email.message}</p>}
        </div>

        <div className="mb-4">
          <label className="block text-gray-700 mb-2">备注(选填)</label>
          <textarea
            {...register('notes')}
            rows="3"
            className="border rounded px-3 py-2 w-full"
          />
        </div>

        <button
          type="submit"
          disabled={!selectedSlot || isSubmitting}
          className={`btn ${!selectedSlot || isSubmitting ? 'btn-disabled' : 'btn-primary'}`}
        >
          {isSubmitting ? '提交中...' : '确认预约'}
        </button>
      </form>
    </div>
  );
}